/* eslint-disable */
import Dexie from 'dexie'
let db = new Dexie('designDB')

db.version(4).stores({
  departments: "departmentId, coId, departmentName, pinyin, parentId, orderNum, code, modifyTime, status",
  employees: "empId, mid, coId, weqiaNo, name, mLogo, jobnumber, code, wid, pinyin, departmentId, departmentName, sex, position, email, mobile, role_id, mSign, cityName, mobileStatus, emailStatus, name_acronym, status, orderNum,modifyTime"
})

db.version(3).stores({
  departments: `departmentId, coId, departmentName, pinyin, parentId, orderNum, code, modifyTime, status`,
  employees: 'empId, mid, coId, weqiaNo, name, mLogo, jobnumber, code, wid, pinyin, departmentId, departmentName, sex, position, email, mobile, role_id, mSign, cityName, mobileStatus, emailStatus, name_acronym, status, orderNum,modifyTime'
})


const DesignDB = new DBInstance(db)

function DBInstance (db) {
  this.db = db
  return this
}

function Department (coId, departmentId, departmentName, pinyin, parentId, orderNum, code, status, modifyTime) {
  this.coId = coId
  this.departmentId = departmentId
  this.departmentName = departmentName
  this.pinyin = pinyin
  this.parentId = parentId
  this.orderNum = orderNum
  this.code = code
  this.modifyTime = modifyTime
  this.status = status
}

function Employess (mid, coId, code, mNo, mName, mLogo, jobnumber, wid, pinyin, departmentId, departmentName, sex, position, email, mobile, role_id, mSign, cityName, mobileStatus, emailStatus, name_acronym, status, orderNum, modifyTime) {
  this.empId = mid + '-' + coId
  this.mid = mid
  this.coId = coId
  this.code = code
  this.mNo = mNo
  this.mName = mName
  this.mLogo = mLogo
  this.jobnumber = jobnumber
  this.wid = wid
  this.pinyin = pinyin
  this.departmentId = departmentId
  this.departmentName = departmentName
  this.sex = sex
  this.position = position
  this.email = email
  this.mobile = mobile
  this.role_id = role_id
  this.mSign = mSign
  this.cityName = cityName
  this.mobileStatus = mobileStatus
  this.emailStatus = emailStatus
  this.name_acronym = name_acronym
  this.status = status
  this.orderNum = orderNum || 0
  this.modifyTime = modifyTime
}

DBInstance.prototype.contactLstTime = function (coId, consumer) {
  let thisInstance = this
  thisInstance.departmentLastTime(coId, function(lastDepart) {
    thisInstance.employeeLastTime(coId, function(lastEmp) {
      consumer(lastDepart, lastEmp)
    })
  })
}

DBInstance.prototype.updateDepartments = function (departments, updateTime) {
  let dbName = 'departments'
  let supplier = function (dept) {
    return new Department(dept.coId, dept.departmentId, dept.departmentName, dept.pinyin, dept.parentId, dept.orderNum, dept.code, dept.status, dept.modifyTime)
  }
  this.bulkSave(dbName, departments, supplier, updateTime)
}

DBInstance.prototype.departmentLastTime = function (coId, consumer) {
  let dbName = 'departments'
  let keyEntity = {
    keyName: 'coId',
    keyValue: coId
  }
  this.findLastUpdateTime(dbName, keyEntity, consumer)
}

DBInstance.prototype.updateEmployees = function (employees, updateTime) {
  let dbName = 'employees'
  let supplier = function (emp) {
    return new Employess (emp.mid, emp.coId, emp.departmentCode, emp.mNo, emp.mName, emp.mLogo, emp.jobnumber, emp.wid, emp.pinyin, emp.departmentId, emp.departmentName, emp.sex, emp.position, emp.email, emp.mobile, emp.role_id, emp.mSign, emp.cityName, emp.mobileStatus, emp.emailStatus, emp.name_acronym, emp.status, emp.orderNum, emp.modifyTime)
  }
  this.bulkSave(dbName, employees, supplier, updateTime)
}

DBInstance.prototype.employeeLastTime = function (coId, consumer) {
  let dbName = 'employees'
  let keyEntity = {
    keyName: 'coId',
    keyValue: coId
  }
  this.findLastUpdateTime(dbName, keyEntity, consumer)
}

DBInstance.prototype.bulkSave = function (dbName, objs, supplier, updateTime) {
  if (!objs || objs.length <= 0) {
    console.log('db save objs is empty')
    return
  }
  let dbObjs = []
  objs.forEach(m => {
    let dbObj = supplier(m, updateTime)
    dbObjs.push(dbObj)
  })
  let thisInstance = this
  thisInstance.db[dbName].bulkPut(dbObjs).then(function (lastKey) {
    console.log('last key is ' + lastKey)
  }).catch(Dexie.BulkError, function (e) {
    console.error('error ' + e)
  })
}

DBInstance.prototype.findLastUpdateTime = function (dbName, keyEntity, consumer) {
  this.db[dbName].where(keyEntity.keyName).equals(keyEntity.keyValue).sortBy('modifyTime').then(res => {
    if (res && res.length > 0) {
      consumer(res[res.length - 1])
    } else {
      consumer(null)
    }
  })
}

DBInstance.prototype.findAll = function (dbName, keyEntity, filter, consumer) {
  return this.db[dbName].where(keyEntity.keyName).equals(keyEntity.keyValue).filter(filter).toArray(consumer)
}

DBInstance.prototype.findDepartments = function (coId, consumer) {
  let keyEntity = {
    keyName: 'coId',
    keyValue: coId
  }
  this.findAll('departments', keyEntity, function(d){
    return d.status === 1
  }, consumer)
}

DBInstance.prototype.findDepartment = function (departmentId, consumer) {
  let keyEntity = {
    keyName: 'departmentId',
    keyValue: departmentId
  }
  this.findAll('departments', keyEntity, function(d){
    return d.status === 1
  }, consumer)
}

DBInstance.prototype.findEmployees = function (coId, payload, consumer) {
  let keyEntity = {
    keyName: 'coId',
    keyValue: coId
  }
  function employeeNormal (e) {
    let status = 1
    // 状态 1 正常 2离职 3客服 4删除
    if (payload.status) {
      status = payload.status
    }
    return e.status === status
  }
  let query = this.db.employees.where(keyEntity.keyName).equals(keyEntity.keyValue)
  // 查找一个部门下的员工
  if (payload.code) {
    query.and(function (m) {
      if (!m.departmentId) {
        return false
      }
      return m.code.startsWith(payload.code)
    })
  }

  // 查找多个部门下的员工 && 未分配部门
  if (payload.codes && payload.codes.length > 0) {
    query.and(function (m) {
      if (payload.codes.includes(m.code) || !m.code) {
        return true
      }
    })
  }

  // 查找未分配部门
  if (payload.undistributed) {
    query.and(function (m) {
      if (!m.departmentId) {
        return true
      }
    })
  }

  if (payload.searchKey) {
    query.and(function (m) {
      if (m.mName && m.mName.toLowerCase().includes(payload.searchKey)) {
        return true
      }
      if (m.mNo && m.mNo.toLowerCase().includes(payload.searchKey)) {
        return true
      }
      if (m.pinyin && m.pinyin.toLowerCase().includes(payload.searchKey)) {
        return true
      }
      if (m.mobile) {
        if (m.mobile.toLowerCase().includes(payload.searchKey)) {
          return true
        }
      }
    })
  }

  if (payload.mid) {
    query.and(function (m) {
      if (m.mid.toLowerCase().includes(payload.mid)) {
        return true
      }
    })
  }
  // 员工角色 1 员工 2 部门管理员 3超级管理员 4 企业管理员
  if (payload.admin) {
    query.and(function (m) {
      if (m.role_id === 2 || m.role_id === 3 || m.role_id === 4) {
        return true
      }
    })
  }

  if (payload.departmentId) {
    query.and(function (m) {
      if (m.departmentId === payload.departmentId) {
        return true
      }
    })
  }

  if (payload.departmentName) {
    query.and(function (m) {
      if (m.departmentName === payload.departmentName) {
        return true
      }
    })
  }

  query.filter(employeeNormal).sortBy('orderNum',function (array) {
    consumer(array.reverse())
  })
}

DBInstance.prototype.employeesCount = function (coId, status, payload = {}) {
  /*
  status
  1: 在职
  1: 离职
  * */
  return new Promise((resolve, reject) => {
    let keyEntity = {
      keyName: 'coId',
      keyValue: coId
    }
    function employeeNormal (e) {
      if (payload.isCompany) {
        // 是否企业管理员
        if (payload.advancedAdmin) {
          return e.status === status
        } else {
          // 获取该员工所有部门下的员工
          if ((payload.codes.includes(e.code) || !e.code) && e.status === status) {
            return true
          }
        }
      } else if (payload.undistributed) {
        // 未分配部门下的员工
        return !e.code && e.status === status
      } else if (payload.codes && payload.codes.length > 0) {
        // 多个部门下的员工
        if (payload.codes.includes(e.code) && e.status === status) {
          return true
        }
      } else if (payload.code) {
        // 某个部门下的员工
        if (e.code) {
          return e.code.startsWith(payload.code) && e.status === status
        }
      } else {
        // 全部员工
        return e.status === status
      }
    }
    this.db.employees.where(keyEntity.keyName).equals(keyEntity.keyValue).filter(employeeNormal).count().then((count) => {
      resolve(count)
    })
  })
}

DBInstance.prototype.adminCount = function (coId, payload = {}) {
  return new Promise((resolve, reject) => {
    let keyEntity = {
      keyName: 'coId',
      keyValue: coId
    }
    function employeeNormal (m) {
      if ((m.role_id === 2 || m.role_id === 3 || m.role_id === 4) && m.status === 1) {
        if (payload.isCompany) {
          if (payload.advancedAdmin) {
            return true
          } else {
            if (payload.codes.includes(m.code) || !m.code) {
              return true
            }
          }
        } else if (payload.undistributed) {
          return !m.code
        } else if (payload.codes && payload.codes.length > 0) {
          if (payload.codes.includes(m.code)) {
            return true
          }
        } else if (payload.code) {
          if (m.code) {
            return m.code.startsWith(payload.code)
          }
        } else {
          return true
        }
      }
    }
    this.db.employees.where(keyEntity.keyName).equals(keyEntity.keyValue).filter(employeeNormal).count().then((count) => {
      resolve(count)
    })
  })
}

export default DesignDB
